// 获取应用实例
const app = getApp();

Page({
  data: {
    searchKey: '',
    currentCategory: 'all',
    categories: [],
    knowledgeList: []
  },

  onLoad() {
    this.loadPageData();
  },

  onPullDownRefresh() {
    this.loadPageData().then(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 加载页面数据
  loadPageData() {
    return Promise.all([
      this.loadCategories(),
      this.loadKnowledgeList()
    ]);
  },

  // 加载分类列表
  loadCategories() {
    return app.request({
      url: '/knowledge/categories',
      method: 'GET'
    }).then(res => {
      if (res.code === 0) {
        this.setData({
          categories: res.data.list
        });
      }
    }).catch(() => {
      app.showError('获取分类列表失败');
    });
  },

  // 加载知识点列表
  loadKnowledgeList() {
    app.showLoading();
    return app.request({
      url: '/knowledge/list',
      method: 'GET',
      data: {
        categoryId: this.data.currentCategory === 'all' ? '' : this.data.currentCategory,
        keyword: this.data.searchKey
      }
    }).then(res => {
      app.hideLoading();
      if (res.code === 0) {
        this.setData({
          knowledgeList: res.data.list
        });
      }
    }).catch(() => {
      app.hideLoading();
      app.showError('获取知识点列表失败');
    });
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKey: e.detail.value
    });
  },

  // 搜索确认
  onSearch() {
    this.loadKnowledgeList();
  },

  // 选择分类
  selectCategory(e) {
    const category = e.currentTarget.dataset.category;
    if (category === this.data.currentCategory) return;
    
    this.setData({
      currentCategory: category
    }, () => {
      this.loadKnowledgeList();
    });
  },

  // 跳转到知识点详情
  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/core-knowledge/detail/detail?id=${id}`
    });
  }
}); 